package com.wlw.admin.sample;

import android.annotation.SuppressLint;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.wlw.admin.pluginlib.utils.DLUtils;

import java.io.File;
import java.util.List;

public class PluginAdapter extends RecyclerView.Adapter<PluginAdapter.PluginViewHolder> {
    private List<PluginItem> pluginItems;
    private OnItemClickListener onItemClickListener;

    public OnItemClickListener getOnItemClickListener() {
        return onItemClickListener;
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    public PluginAdapter(List<PluginItem> pluginItems) {
        this.pluginItems = pluginItems;
    }

    @NonNull
    @Override
    public PluginViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        return new PluginViewHolder(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_plugin, viewGroup, false));
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onBindViewHolder(@NonNull PluginViewHolder pluginViewHolder, int i) {
        PluginItem item = pluginItems.get(i);
        Context context = pluginViewHolder.itemView.getContext();
        pluginViewHolder.ivIcon.setImageDrawable(DLUtils.getAppIcon(context, item.pluginPath));
        pluginViewHolder.tvAppName.setText(DLUtils.getAppLabel(context, item.pluginPath));
        pluginViewHolder.tvApkName.setText(item.pluginPath.substring(item.pluginPath.lastIndexOf((File.separatorChar) + 1)));
        pluginViewHolder.tvPackageName.setText(item.packageInfo.applicationInfo.packageName + "\n"
                + item.launcherActivityName + "\n"
                + item.launcherServiceName);
        pluginViewHolder.tvApkSize.setText(item.apkSize / 1024 / 1024 + "M");
        pluginViewHolder.itemView.setOnClickListener(v->{
            if(onItemClickListener!=null){
                onItemClickListener.onItemClick(i);
            }
        });
    }

    @Override
    public int getItemCount() {
        return pluginItems.size();
    }

    class PluginViewHolder extends RecyclerView.ViewHolder {
        ImageView ivIcon;
        TextView tvAppName, tvApkName, tvPackageName, tvApkSize;

        public PluginViewHolder(@NonNull View itemView) {
            super(itemView);
            ivIcon = itemView.findViewById(R.id.iv_icon);
            tvAppName = itemView.findViewById(R.id.tv_app_name);
            tvApkName = itemView.findViewById(R.id.tv_apk_name);
            tvPackageName = itemView.findViewById(R.id.tv_package_name);
            tvApkSize = itemView.findViewById(R.id.tv_apk_size);
        }
    }
}
